package com.ruicar.afs.cloud.auth.component;


import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.security.constant.SystemInnerConstants;
import com.ruicar.afs.cloud.common.core.security.feign.Oauth2OperationService;
import com.ruicar.afs.cloud.common.core.security.service.AfsSysAdminRootService;
import com.ruicar.afs.cloud.common.core.util.Base64Util;
import com.ruicar.afs.cloud.common.core.util.ClientTypeUtil;
import com.ruicar.afs.cloud.common.core.util.SpringContextHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@AllArgsConstructor
public class SysAutoLogin implements ApplicationListener<ApplicationReadyEvent> {

    private static final Map<String,String> HEADER = new HashMap<>();
    private static final Map<String,String> PARAMS = new HashMap<>();
    static {
        HEADER.put(CommonConstants.AUTHORIZATION, "Basic " + Base64Util.encode((ClientTypeUtil.ClientTypeEnum.SYSTEM_INNER.getClientId() + ":" + ClientTypeUtil.ClientTypeEnum.SYSTEM_INNER.getClientSecret()).getBytes()));
        PARAMS.put(CommonConstants.USERNAME,SystemInnerConstants.SYSTEM_ADMIN);
        PARAMS.put(CommonConstants.PASSWORD,CommonConstants.DEFAULT_PASS);
        PARAMS.put(CommonConstants.GRANT_TYPE, "password");
    }

    private final AfsSysAdminRootService afsSysAdminRootService;
    private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = Executors.newScheduledThreadPool(1);


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        systemAutoLogin();
    }

    private  boolean doLogin() throws Exception{
        Object obj = SpringContextHolder.getBean(Oauth2OperationService.class).login(PARAMS, HEADER);
        if(obj instanceof Map){
            Map map = (Map) obj;
            if(map.containsKey("access_token")){
                JSONObject tokenInfo = new JSONObject();
                tokenInfo.put(CommonConstants.ACCESS_TOKEN,map.get("access_token"));
                tokenInfo.put(CommonConstants.UPD_TIME,System.currentTimeMillis());
                afsSysAdminRootService.setCacheToken(tokenInfo);
                return true;
            }
        }
        return false;
    }
    public void systemAutoLogin(){
        SCHEDULED_EXECUTOR_SERVICE.scheduleWithFixedDelay(()->{
            boolean flag = false;
            while(!flag) {
                try {
                    JSONObject tokenInfo = afsSysAdminRootService.getCacheToken();
                    if(tokenInfo.size()==0) {
                        flag = doLogin();
                    }else{
                        if((System.currentTimeMillis()-tokenInfo.getLong(CommonConstants.UPD_TIME))>25*60*1000){
                            flag = doLogin();
                        }else {
                            flag = true;
                        }
                    }
                }catch (Exception e){
                    if(e instanceof IllegalStateException && (e.getMessage().equals("Provider is shut down and can not longer provide resources")
                            || e.getMessage().equals("Cannot connect, Event executor group is terminated")
                    )){
                        flag = true;
                    }
                    log.error("自动登录失败",e);
                }finally {
                    ThreadUtil.sleep(300);
                }
            }
        },1,10, TimeUnit.SECONDS);
    }
}
